
use serde::{Serialize, Deserialize};


#[derive(Serialize, Deserialize)]
pub struct VecF64 {
    pub name: String,
    pub items: Vec<f64>,
    pub min: f64,
    pub max: f64,
}


impl VecF64 {
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            items: vec![],
            min: 0.0,
            max: 0.0,
        }
    }

    pub fn len(&self) -> usize {
        self.items.len()
    }
    pub fn items(&self) -> &Vec<f64> {
        &self.items
    }
    // pub fn items_mut(&mut self) -> &mut Vec<f64> {
    //     &mut self.items
    // }
}

impl VecF64 {
    pub fn to_print_items(&self) -> String {
        let len = self.items.len();
        if len <= 10 {
            return format!("{:?}", self.items);
        }

        let mut buf = format!("[{}", self.items[0]);
        for index in 1..5 {
            buf.push_str(&format!(", {}", self.items[index]));
        }
        buf.push_str(", ...");
        for index in (1..6).rev() {
            buf.push_str(&format!(", {}", self.items[len - index]));
        }
        buf.push(']');

        buf
    }
    pub fn to_print(&self) -> String {
        format!("array 【{}】: len = {}, min={}, max={}, {}",
            self.name, self.len(), self.min, self.max, self.to_print_items())
    }

}

impl VecF64 {
    pub fn push(&mut self, val: f64) {
        if self.items.len() == 0 {
            self.min = val;
            self.max = val;
        } else {
            self.min = self.min.min(val);
            self.max = self.max.max(val);
        }
        self.items.push(val);
    }
}


#[test]
fn test_arrayf64() {
    // log4rs_mod::init_by_off2("common_uu,hot_lib_reloader,jsonrpsee_server,hyper,sled,jsonrpsee_client_transport,jsonrpsee_core,isahc,orm_mysql",
    //     "utils_rs".to_string()).unwrap();
    let mut array = VecF64::new("测试");
    array.push(6.0);
    array.push(5.0);
    array.push(1.0);
    array.push(3.0);
    array.push(2.0);
    array.push(4.0);
    array.push(8.0);
    array.push(9.0);
    array.push(10.0);
    array.push(7.0);
    
    assert_eq!(array.len(), 10);

    println!("items: {:?}, min={}, max={}", array.items, array.min, array.max);
}


pub fn min_max(items: &[f64]) -> (usize, f64, usize, f64) {
    if items.len() == 0 {
        return (0, 0.0, 0, 0.0);
    }
    let mut index_min = 0;
    let mut index_max = 0;

    let mut min = items[0];
    let mut max = items[0];
    for index in 2..items.len() {
        let val = items[index];
        if val < min {
            min = val;
            index_min = index;
        }
        if val > max {
            max = val;
            index_max = index;
        }
    }
    (index_min, min, index_max, max)
}